var mticket = new MaintenanceTicket(JSON.parse(localStorage.getItem('config')));

mticket.setFormDefaultValues = function(issueObject)
{
    // if not bug
    let type = jQuery('#type-val').text().trim().toLocaleUpperCase();
    // if issueObject.fields.customfield_13431.value=='Code change',  add to condtion ?
    if(type=='BUG') {
        // remove Done Status
        this.formSchema.schema.fields.properties.status.properties.name.enum.push("Ready for Release");
    } else {
        // remove bug related fild
        this.formSchema.schema.fields.properties.status.properties.name.enum.push("Done");
        let formElement = [];
        this.formSchema.form.forEach((item, idx) => {
            if (item.key!=='fields.customfield_15819' &&
                item.key!=='fields.customfield_15820'
                ) {
                formElement.push(item);
            }
        });
        this.formSchema.form = formElement;
    }

    if (issueObject.fields.status) {
        if (issueObject.fields.status.name) {
            this.formSchema.schema.fields.properties.status.properties.name.default = issueObject.fields.status.name;
        }
    }

    if (issueObject.fields.customfield_13431) {
        if (issueObject.fields.customfield_13431.value) {
            this.formSchema.schema.fields.properties.customfield_13431.properties.value.default = issueObject.fields.customfield_13431.value;
        }
    }

    if (issueObject.fields.customfield_15300) {
        this.formSchema.schema.fields.properties.customfield_15300.properties.value.default = issueObject.fields.customfield_15300.value;
    }

    if (issueObject.fields.customfield_14800) {
        let region  = [];
        issueObject.fields.customfield_14800.forEach((item, idx) => {
            region.push(item.value);
        });
        this.formSchema.schema.fields.properties.customfield_14800.default = region;
    }

    if (issueObject.fields.customfield_13423) {
        let countries = [];
        issueObject.fields.customfield_13423.forEach((item, idx) => {
            countries.push(item.value);
        });
        this.formSchema.schema.fields.properties.customfield_13423.default = countries;
    }

    if (issueObject.fields.customfield_15819) {
        this.formSchema.schema.fields.properties.customfield_15819.default = issueObject.fields.customfield_15819;
    }

    // customfield_15820
    if (issueObject.fields.customfield_15820) {
        if (issueObject.fields.customfield_15820.value) {
            this.formSchema.schema.fields.properties.customfield_15820.properties.value.default = issueObject.fields.customfield_15820.value;
        }
    }
    console.log('##issueObject', issueObject);
    console.log('##forms', this.formSchema.schema);
}

mticket.formSchema = {
    "schema": {
        "fields": {
            "type": "object",
            "title": "Fields",
            "properties": {
                "status": {
                    "type":"object",
                    "properties": {
                        "name": {
                            "type": "string",
                            "title": "Status",
                            "description":"Task 最终状态为 Done, BUG 最终状态为 Ready ror Release。问题修复或者反馈了，但需要等待 SA 或客户反馈应该选 Waiting On Customer。",
                            "enum": [
                                "Open",
                                "In Progress",
                                "In Testing",
                                "Waiting on Customer"
                              //"Ready for Release",
                              //"Done"
                            ],
                            "default": "Open"
                        }
                    }
                },
                "customfield_13431": {
                    "type": "object",
                    "properties": {
                        "value": {
                            "type": "string",
                            "title": "Ticket Action",
                            "description": "如果最终有代码修改，那么需要联系管理员将当前任务类型改为BUG。然后再更新字段和状态。",
                            "enum": [
                                "None",
                                "Code change",
                                "Update information",
                                "Verification",
                                "Update status",
                                "Configuration",
                                "Export data",
                                "Import data",
                                "Refresh index",
                                "Others"
                            ],
                            "default": jQuery('#type-val').text().trim().toLocaleUpperCase()==="BUG" ? "Code change" : "None"
                        }
                    }
                },
                "customfield_15300": {
                    "type": "object",
                    "properties": {
                        "value": {
                            "type": "string",
                            "title": "Area Impact",
                            "description": "出问题的属于哪部分业务",
                            "enum": [
                                "None",
                                "FE - Order",
                                "BE - Order",
                                "FE - Quote",
                                "BE - Quote",
                                "FE - Payment",
                                "BE - Payment",
                                "FE - Invoice",
                                "BE - Invoice",
                                "FE - Shipping",
                                "BE - Shipping",
                                "FE - Delivery",
                                "BE - Delivery",
                                "FE - Cart",
                                "BE - Cart",
                                "FE - Stock",
                                "BE - Stock",
                                "FE - Checkout",
                                "BE - Checkout",
                                "FE - Pincode / Postcode",
                                "BE - Pincode / Postcode",
                                "FE - Category",
                                "BE - Category",
                                "FE - Homepage",
                                "FE - HP Money",
                                "FE - CMS",
                                "FE - PDP",
                                "FE - PLP",
                                "FE - Customer",
                                "BE - Customer",
                                "FE - Account",
                                "BE - Account",
                                "BE - Feed",
                                "FE - Tagging",
                                "BE - Tagging",
                                "FE - UX",
                                "BE - UX",
                                "FE - Carepack",
                                "FE - SEO",
                                "FE - Search",
                                "FE - SMS",
                                "BE - SMS",
                                "FE - Email",
                                "BE - Email",
                                "FE - URL",
                                "BE - URL",
                                "BE - ISR",
                                "BE - API",
                                "BE - Report",
                                "BE - Webhook",
                                "BE - RPL/GTS",
                                "FE - Coupon",
                                "FE - Subscription",
                                "FE - BazaarVoice"
                            ],
                            "default": "None"
                        }
                    }
                },
                "customfield_14800": {
                    "title": "Regions",
                    "type": "string",
                    "description": "这个问题影响覆盖哪些地区",
                    "enum": [
                        "None",
                        "AP",
                        "LATAM"
                    ],
                    "default": "None"
                },
                "customfield_13423": {
                    "title": "Country Covered",
                    "type": "string",
                    "description": "这个问题影响覆盖哪些地区，如果问题只在一个地区暴露出来，就需要看最后修复的代码那些地区会用到。",
                    "enum": [
                        "None",
                        "AR",
                        "AU",
                        "BR",
                        "CL",
                        "CN",
                        "CO",
                        "HK",
                        "IN",
                        "ID",
                        "KR",
                        "MX",
                        "MY",
                        "NZ",
                        "PE",
                        "SG",
                        "TH",
                        "ALL",
                        "AP",
                        "LAM"
                    ],
                    "default": ["None"]
                },
                "customfield_15819": {
                    "type": "string",
                    "title": "Code Branch",
                    "description": "修复问题的分支，应该填 Support 主分支。",
                    "default": ""
                },
                "customfield_15820": {
                    "type": "object",
                    "properties": {
                        "value": {
                            "type": "string",
                            "title": "Code Merged",
                            "description": "是否已经最后发起了向 develop 的合并请求。",
                            "enum": [
                                "None",
                                "No",
                                "Yes",
                                "No code change"
                            ],
                            "default": jQuery('#type-val').text().trim().toLocaleUpperCase()==="BUG" ? "No" : "No code change"
                        }
                    }
                },
                "comment": {
                    "type": "textarea",
                    "title": "  ",
                    "description": "WOC 状态必须 @SA 告知遇到的问题，需要什么样的帮助，导致的需要 WOC"
                }
            }
        }
    },
    "form": [
        {
            "key": "fields.status",
            "onChange": function(evt) {
                var value = $(evt.target).val();
                if (value=="Waiting on Customer") {
                    jQuery('.jsonform-error-fields---comment textarea').removeClass('hidden');
                } else {
                    jQuery('.jsonform-error-fields---comment textarea').addClass('hidden');
                }
            }
        },
        {
            "key": "fields.comment",
            "fieldHtmlClass":"hidden"
        },
        {
            "key": "fields.customfield_13431"
        },
        {
            "key": "fields.customfield_15819"
        },
        {
            "key": "fields.customfield_15820"
        },
        {
            "key": "fields.customfield_15300"
        },
        {
            "type": "multipleSelect",
            "key": "fields.customfield_14800"
        },
        {
            "type": "multipleSelect",
            "key": "fields.customfield_13423"
        }
    ]
};

mticket.formSchema.onSubmitValid = function(values) {
    let LIMIT_STRING = 'NONE';
    let keys = Object.keys(values.fields);
    let pass = true;

    try {
        keys.forEach((field, idx) => {
            let item = values.fields[field];
            let type = Object.prototype.toString.call(values.fields[field]);
            switch (type) {
                case '[object Array]':
                    item.forEach((_item, _idx) => {
                        if (pass) {
                            pass = _item.value.trim().toLocaleUpperCase() != LIMIT_STRING;
                        }
                    });
                    break;
                case '[object Object]':
                    if (item.hasOwnProperty('value')) {
                        if (pass) {
                            pass = item.value.trim().toLocaleUpperCase() != LIMIT_STRING;
                        }
                    } else if(item.hasOwnProperty('name')) {
                        if (pass) {
                            pass = item.name.trim().toLocaleUpperCase() != LIMIT_STRING;
                        }
                    } else {
                        pass = false;
                    }
                    break;
                case '[object String]':
                    if (pass) {
                        pass = item.trim().toLocaleUpperCase() != LIMIT_STRING;
                    }
                    break;
            }
            if (!pass) {
                throw new Error(field);
            }
        });
    } catch (e) {
        let xpath = '.jsonform-error-fields---' + e.message.replace('Error: ', '') + '---value label';
        alert(jQuery(xpath).text() + ' 的值不对！');
        jQuery('#sync-loading').remove();
        console.log('#valiate error', e);
    }
    return pass;
}


var sBugWorkflow = [
    "Investigation",
    "QA Confirm Request",
    "Pass Verification",
    "Reopen"
];
var sTaskWorkflow = [
    "To Do",
    "In Progress",
    "Done"
];
var tBugWorkflow = [
    "Open",
    "In Progress",
    "In Testing",
    "Waiting on Customer",
    "Ready for Release"
];
var tTaskWorkflow = [
    "Open",
    "In Progress",
    "In Testing",
    "Done",
    "Waiting on Customer",
];


var validateTypeExc = null;
var validateType = function()
{
    if (!jQuery('#viewissue-devstatus-panel').is(':hidden') && jQuery('#devstatus-container li.devstatus-entry').html().length) {

        if (jQuery('#type-val').text().trim().toLocaleUpperCase()==='TASK') {
            jQuery('#devstatus-container  li.devstatus-entry').html('<span style="color:orangered;">该任务类型是Task,不允许创建分支;如需创建分支请联系管理员修改任务类型为Bug</span>');
            jQuery('#viewissue-devstatus-panel').show();
        }
        if (jQuery('#type-val').text().trim().toLocaleUpperCase()==='BUG') {
            var bugTipHtml = `
            <li><span style="color:orangered;">分支合并顺序:<br/>
            Bug Ticket 分支 ----> Support Ticket 分支 ----> test/develop/master 分支</span>
            </li>
            `;
            jQuery('#viewissue-devstatus-panel ul.devstatus-entry').before(bugTipHtml);
        }
        clearInterval(validateTypeExc);
    }
}
if (
    jQuery('#type-val').text().trim().toLocaleUpperCase()==='TASK' ||
    jQuery('#type-val').text().trim().toLocaleUpperCase()==='BUG' ||
    window.location.href.indexOf('create-branch') > 0
) {
    validateTypeExc = setInterval(validateType, 1000);
}